/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rlpw.swing.table;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.TableCellEditor;

/**
 *
 * @author weinpau
 */
public class ColorEditor extends AbstractCellEditor implements TableCellEditor {

    private JPanel panel = new JPanel(new BorderLayout());
    private JColorChooser colorChooser;
    private Color currentColor;
    private JDialog dialog;
    private ColorRenderer renderer = new ColorRenderer();

    public ColorEditor() {

        final JButton button = new JButton(new javax.swing.plaf.metal.MetalComboBoxIcon());

        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                colorChooser.setColor(currentColor);
                dialog.setVisible(true);
                fireEditingStopped();
            }
        });
        button.setBorderPainted(false);
        colorChooser = new JColorChooser();
        dialog = JColorChooser.createDialog(button, "Pick a Color", true, colorChooser, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                currentColor = colorChooser.getColor();
            }
        }, null);

        panel.add("East", button);

    }

    public Object getCellEditorValue() {
        return currentColor;
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {



        currentColor = (Color) value;
        JLabel label = (JLabel) renderer.getTableCellRendererComponent(table, value, isSelected, isSelected, row, column);
        label.setOpaque(false);

        panel.add("Center", label);

        panel.setOpaque(true);

        if (isSelected) {
            panel.setForeground(table.getSelectionForeground());
            panel.setBackground(table.getSelectionBackground());
        } else {

            Color aColor = UIManager.getColor("Table.alternateRowColor");

            if (row % 2 == 1 || aColor == null) {
                panel.setBackground(aColor);
            } else {
                panel.setOpaque(false);
                panel.setBackground(table.getBackground());
            }

        }

        return panel;
    }
}